package com.jim.util;

import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.jim.to.Article;
 
public class RSSReader {
 
	private static RSSReader instance = null;
	
	private RSSReader() {
	}
	
	public static RSSReader getInstance() {
		if(instance == null) {
			instance = new RSSReader();	
		}
		return instance;
	}
	
	public List<Article> getNews(int count) {
		try {
 
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			URL u = new URL("http://www.jimjin.cn/?feed=rss2");
			
			Document doc = builder.parse(u.openStream());
			
			NodeList nodes = doc.getElementsByTagName("item");
			List<Article> articleList = new ArrayList<Article>();
			for(int i=0;i<nodes.getLength();i++) {
				if (i>count){
					break;
				}
				Element element = (Element)nodes.item(i);
				
				Article article = new Article();
				article.setTitle(getElementValue(element,"title"));
				article.setLink(getElementValue(element,"title"));
				article.setPublishDate(Date.valueOf(getElementValue(element,"pubDate")));
				article.setDescription(getElementValue(element,"description"));
				articleList.add(article);
			}//for	
			return articleList;
		}//try
		catch(Exception ex) {
		}
		return new ArrayList<Article>();
		
	}
		
		
		private String getCharacterDataFromElement(Element e) {
			try {
				Node child = e.getFirstChild();
				if(child instanceof CharacterData) {
					CharacterData cd = (CharacterData) child;
					return cd.getData();
				}
			}
			catch(Exception ex) {
				
			}
			return "";			
		} //private String getCharacterDataFromElement
		
		protected float getFloat(String value) {
			if(value != null && !value.equals("")) {
				return Float.parseFloat(value);	
			}
			return 0;
		}
		
		protected String getElementValue(Element parent,String label) {
			return getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));	
		}
}

